<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="计划ID" prop="planId">
            <el-input
                v-model="queryParams.planId"
                placeholder="请输入计划ID"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备ID" prop="deviceId">
            <el-input
                v-model="queryParams.deviceId"
                placeholder="请输入设备ID"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="recordType">
            <template #label>
              <el-tooltip content="记录类型: 1-维护记录, 2-检查记录" placement="top">
                <span>记录类型 <el-icon><InfoFilled /></el-icon></span>
              </el-tooltip>
            </template>
            <el-select v-model="queryParams.recordType" placeholder="请选择记录类型" clearable style="width: 100%;">
              <el-option
                  v-for="dict in record_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="recordResult">
            <template #label>
              <el-tooltip content="记录结果: 1-正常, 2-异常, 3-待确认" placement="top">
                <span>记录结果 <el-icon><InfoFilled /></el-icon></span>
              </el-tooltip>
            </template>
            <el-select v-model="queryParams.recordResult" placeholder="请选择记录结果" clearable style="width: 100%;">
              <el-option
                  v-for="dict in record_result"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="记录时间" prop="recordTime">
            <el-date-picker clearable
                            v-model="queryParams.recordTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择记录时间"
                            style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="记录人" prop="recordBy">
            <el-input
                v-model="queryParams.recordBy"
                placeholder="请输入记录人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item class="search-buttons-aligned">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 统计图表区域 START -->
    <el-card class="box-card mb8 chart-section">
      <template #header>
        <div class="card-header">
          <span>维护记录概览统计</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="12">
          <div id="recordTypeChart" class="chart-container"></div>
        </el-col>
        <el-col :span="12">
          <div id="recordResultChart" class="chart-container"></div>
        </el-col>
      </el-row>
    </el-card>
    <!-- 统计图表区域 END -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['maintenance:record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['maintenance:record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['maintenance:record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['maintenance:record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="id" width="80" />
      <el-table-column label="计划ID" align="center" prop="planId" width="100" />
      <el-table-column label="设备ID" align="center" prop="deviceId" width="100" />
      <el-table-column prop="recordType" align="center" min-width="120px">
        <template #header>
          <el-tooltip content="记录类型: 1-维护记录, 2-检查记录" placement="top">
            <span>记录类型 <el-icon><InfoFilled /></el-icon></span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag :options="record_type" :value="scope.row.recordType"/>
        </template>
      </el-table-column>
      <!-- 记录内容字段优化：剥离HTML，截断显示，悬停显示全部 -->
      <el-table-column label="记录内容" align="center" prop="recordContent" min-width="180px">
        <template #default="scope">
          <span v-if="scope.row.recordContent">
            <el-tooltip :content="stripHtmlTags(scope.row.recordContent)" placement="top">
              <span class="truncated-text">{{ stripHtmlTags(scope.row.recordContent) }}</span>
            </el-tooltip>
          </span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column prop="recordResult" align="center" min-width="120px">
        <template #header>
          <el-tooltip content="记录结果: 1-正常, 2-异常, 3-待确认" placement="top">
            <span>记录结果 <el-icon><InfoFilled /></el-icon></span>
          </el-tooltip>
        </template>
        <template #default="scope">
          <dict-tag :options="record_result" :value="scope.row.recordResult"/>
        </template>
      </el-table-column>
      <!-- 异常描述字段优化：剥离HTML，截断显示，悬停显示全部 -->
      <el-table-column label="异常描述" align="center" prop="abnormalDesc" min-width="180px">
        <template #default="scope">
          <span v-if="scope.row.abnormalDesc">
            <el-tooltip :content="stripHtmlTags(scope.row.abnormalDesc)" placement="top">
              <span class="truncated-text">{{ stripHtmlTags(scope.row.abnormalDesc) }}</span>
            </el-tooltip>
          </span>
          <span v-else></span>
        </template>
      </el-table-column>
      <!-- 处理建议字段优化：剥离HTML，截断显示，悬停显示全部 -->
      <el-table-column label="处理建议" align="center" prop="suggestions" min-width="180px">
        <template #default="scope">
          <span v-if="scope.row.suggestions">
            <el-tooltip :content="stripHtmlTags(scope.row.suggestions)" placement="top">
              <span class="truncated-text">{{ stripHtmlTags(scope.row.suggestions) }}</span>
            </el-tooltip>
          </span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="记录时间" align="center" prop="recordTime" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录人" align="center" prop="recordBy" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['maintenance:record:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['maintenance:record:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改维护记录对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="计划ID" prop="planId">
          <el-input v-model="form.planId" placeholder="请输入计划ID" />
        </el-form-item>
        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备ID" />
        </el-form-item>
        <el-form-item prop="recordType">
          <template #label>
            <el-tooltip content="记录类型: 1-维护记录, 2-检查记录" placement="top">
              <span>记录类型 <el-icon><InfoFilled /></el-icon></span>
            </el-tooltip>
          </template>
          <el-select v-model="form.recordType" placeholder="请选择记录类型" style="width: 100%;">
            <el-option
                v-for="dict in record_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="记录内容" prop="recordContent">
          <editor v-model="form.recordContent" :min-height="192"/>
        </el-form-item>
        <el-form-item prop="recordResult">
          <template #label>
            <el-tooltip content="记录结果: 1-正常, 2-异常, 3-待确认" placement="top">
              <span>记录结果 <el-icon><InfoFilled /></el-icon></span>
            </el-tooltip>
          </template>
          <el-select v-model="form.recordResult" placeholder="请选择记录结果" style="width: 100%;">
            <el-option
                v-for="dict in record_result"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="异常描述" prop="abnormalDesc">
          <el-input v-model="form.abnormalDesc" type="textarea" placeholder="请输入内容" :rows="3" />
        </el-form-item>
        <el-form-item label="处理建议" prop="suggestions">
          <el-input v-model="form.suggestions" type="textarea" placeholder="请输入内容" :rows="3" />
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker clearable
                          v-model="form.recordTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择记录时间"
                          style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="记录人" prop="recordBy">
          <el-input v-model="form.recordBy" placeholder="请输入记录人" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/maintenance/record";
import { InfoFilled } from '@element-plus/icons-vue'; // 引入图标
import * as echarts from 'echarts'; // 引入 ECharts
import { onMounted, onBeforeUnmount, ref, reactive, toRefs, getCurrentInstance } from 'vue'; // 明确引入Vue Composition API函数

const { proxy } = getCurrentInstance();
const { record_result, record_type } = proxy.useDict('record_result', 'record_type');

const recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// ECharts 实例引用
let recordTypeChartInstance = null;
let recordResultChartInstance = null;

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planId: null,
    deviceId: null,
    recordType: null,
    recordContent: null,
    recordResult: null,
    abnormalDesc: null,
    suggestions: null,
    recordTime: null,
    recordBy: null,
  },
  rules: {
    planId: [
      { required: true, message: "计划ID不能为空", trigger: "blur" }
    ],
    deviceId: [
      { required: true, message: "设备ID不能为空", trigger: "blur" }
    ],
    recordType: [
      { required: true, message: "记录类型不能为空", trigger: "change" }
    ],
    recordContent: [
      { required: true, message: "记录内容不能为空", trigger: "blur" }
    ],
    recordResult: [
      { required: true, message: "记录结果不能为空", trigger: "change" }
    ],
    recordTime: [
      { required: true, message: "记录时间不能为空", trigger: "blur" }
    ],
    recordBy: [
      { required: true, message: "记录人不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/**
 * 节流函数
 */
const throttle = (func, delay) => {
  let timeoutId;
  let lastArgs;
  let lastThis;

  return function(...args) {
    lastArgs = args;
    lastThis = this;

    if (!timeoutId) {
      timeoutId = setTimeout(() => {
        func.apply(lastThis, lastArgs);
        timeoutId = null;
        lastArgs = null;
        lastThis = null;
      }, delay);
    }
  };
};

/**
 * 根据数据聚合图表所需的数据
 * @param {Array} dataList - 维护记录列表数据
 */
function aggregateChartData(dataList) {
  if (!dataList || dataList.length === 0) {
    updateRecordTypeChart([]);
    updateRecordResultChart([]);
    return;
  }

  const typeCounts = {};
  const resultCounts = {};

  dataList.forEach(item => {
    // 聚合记录类型
    const typeDict = record_type.value.find(d => parseInt(d.value) === item.recordType);
    const typeLabel = typeDict ? typeDict.label : '未知类型';
    typeCounts[typeLabel] = (typeCounts[typeLabel] || 0) + 1;

    // 聚合记录结果
    const resultDict = record_result.value.find(d => parseInt(d.value) === item.recordResult);
    const resultLabel = resultDict ? resultDict.label : '未知结果';
    resultCounts[resultLabel] = (resultCounts[resultLabel] || 0) + 1;
  });

  const typeSeriesData = Object.keys(typeCounts).map(key => ({
    name: key,
    value: typeCounts[key]
  }));

  const resultSeriesData = Object.keys(resultCounts).map(key => ({
    name: key,
    value: resultCounts[key]
  }));

  updateRecordTypeChart(typeSeriesData);
  updateRecordResultChart(resultSeriesData);
}

/**
 * 初始化并更新记录类型分布图 (饼图)
 * @param {Array} seriesData - 图表数据
 */
function updateRecordTypeChart(seriesData) {
  const chartDom = document.getElementById('recordTypeChart');
  if (!chartDom) return;

  if (!recordTypeChartInstance) {
    recordTypeChartInstance = echarts.init(chartDom);
  }

  const option = {
    title: {
      text: '记录类型分布',
      subtext: '基于当前查询结果',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '记录类型',
        type: 'pie',
        radius: '50%',
        center: ['50%', '60%'],
        data: seriesData.length > 0 ? seriesData : [{ value: 1, name: '暂无数据', itemStyle: { color: '#ccc' } }],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: seriesData.length > 0,
          formatter: '{b} ({d}%)'
        },
        labelLine: {
          show: seriesData.length > 0
        },
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: function (idx) {
          return Math.random() * 200;
        }
      }
    ]
  };
  recordTypeChartInstance.setOption(option);
}

/**
 * 初始化并更新记录结果分布图 (饼图)
 * @param {Array} seriesData - 图表数据
 */
function updateRecordResultChart(seriesData) {
  const chartDom = document.getElementById('recordResultChart');
  if (!chartDom) return;

  if (!recordResultChartInstance) {
    recordResultChartInstance = echarts.init(chartDom);
  }

  const option = {
    title: {
      text: '记录结果分布',
      subtext: '基于当前查询结果',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '记录结果',
        type: 'pie',
        radius: '50%',
        center: ['50%', '60%'],
        data: seriesData.length > 0 ? seriesData : [{ value: 1, name: '暂无数据', itemStyle: { color: '#ccc' } }],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: seriesData.length > 0,
          formatter: '{b} ({d}%)'
        },
        labelLine: {
          show: seriesData.length > 0
        },
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: function (idx) {
          return Math.random() * 200;
        }
      }
    ]
  };
  recordResultChartInstance.setOption(option);
}

// 监听窗口大小变化以调整图表尺寸
const resizeCharts = throttle(() => {
  recordTypeChartInstance?.resize();
  recordResultChartInstance?.resize();
}, 200);

// HTML标签剥离函数
function stripHtmlTags(htmlString) {
  if (!htmlString) return '';
  const doc = new DOMParser().parseFromString(htmlString, 'text/html');
  return doc.body.textContent || '';
}

/** 查询维护记录列表 */
function getList() {
  loading.value = true;
  listRecord(queryParams.value).then(response => {
    // 确保数据类型转换，特别是对于 select 绑定的字段
    recordList.value = response.rows.map(item => ({
      ...item,
      recordType: item.recordType !== null ? Number(item.recordType) : null,
      recordResult: item.recordResult !== null ? Number(item.recordResult) : null
    }));
    total.value = response.total;
    loading.value = false;
    // 数据加载完成后更新图表
    aggregateChartData(recordList.value);
  }).catch(() => {
    // 请求失败时也应清空或更新图表为无数据状态
    console.error("Failed to fetch record list.");
    aggregateChartData([]);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    planId: null,
    deviceId: null,
    recordType: null,
    recordContent: null,
    recordResult: null,
    abnormalDesc: null,
    suggestions: null,
    recordTime: null,
    recordBy: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null
  };
  proxy.resetForm("recordRef"); // 重置表单验证状态
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  // 显式重置下拉框字段为 null，确保清空显示
  queryParams.value.recordType = null;
  queryParams.value.recordResult = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加维护记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getRecord(_id).then(response => {
    // 确保从后端获取的数据类型正确，特别是对于 select 绑定的字段
    response.data.recordType = response.data.recordType !== null ? Number(response.data.recordType) : null;
    response.data.recordResult = response.data.recordResult !== null ? Number(response.data.recordResult) : null;
    form.value = response.data;
    open.value = true;
    title.value = "修改维护记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList(); // 刷新列表和图表数据
        });
      } else {
        addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList(); // 刷新列表和图表数据
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除维护记录编号为"' + _ids + '"的数据项？').then(function() {
    return delRecord(_ids);
  }).then(() => {
    getList(); // 刷新列表和图表数据
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('maintenance/record/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`);
}

// Mounted 生命周期钩子：初始化图表并添加窗口resize监听
onMounted(() => {
  // 在获取列表数据之前，先初始化空的图表，防止DOM还没渲染好就尝试获取元素
  updateRecordTypeChart([]); // 传入空数组初始化无数据状态
  updateRecordResultChart([]); // 传入空数组初始化无数据状态

  // 添加窗口resize事件监听
  window.addEventListener('resize', resizeCharts);

  // 第一次加载列表数据
  getList();
});

// Unmounted 生命周期钩子：销毁图表实例并移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts);
  recordTypeChartInstance?.dispose(); // 销毁 ECharts 实例，防止内存泄漏
  recordResultChartInstance?.dispose();
});
</script>

<style scoped>
/* 统一的表单标签和图标样式 */
.el-form-item__label span {
  display: flex;
  align-items: center;
  white-space: nowrap; /* 防止标签文本换行 */
}
.el-form-item__label .el-icon {
  margin-left: 4px; /* 图标与文字间距 */
  font-size: 14px;
  cursor: help; /* 提示可悬浮 */
}

/* 搜索按钮组的对齐样式，去除默认左边距以更好地对齐 */
.search-buttons-aligned {
  margin-left: 0 !important;
  white-space: nowrap; /* 确保按钮不换行 */
}

/* 表格内长文本截断样式 */
.truncated-text {
  display: block; /* 确保占满宽度 */
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 显示省略号 */
  max-width: 100%; /* 限制最大宽度 */
}

/* 统计图表区域样式 */
.chart-section {
  margin-bottom: 20px; /* 图表卡片与下方表格的间距 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
}

.chart-container {
  height: 300px; /* 为图表设置固定高度 */
  width: 100%; /* 宽度自动填充父容器 */
}
</style>
